package org.example.main.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.example.main.entity.House;
import org.example.main.utils.CommonResult;
import org.example.main.entity.RentalApplication;
import org.example.main.service.HouseService;
import org.example.main.service.RecordService;
import org.example.main.entity.Record;
import org.example.main.service.RentalApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@CrossOrigin
@Tag(name = "租聘审核管理",description = "租聘申请管理相关接口")
@RestController
@RequestMapping("/rental")
public class RentalApplicationController {

    @Autowired
    private RentalApplicationService rentalApplicationService;

    @Autowired
    private HouseService houseService;

    @Autowired
    private RecordService recordService;

    @Operation(summary = "租客申请租/退房")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "申请成功"),
            @ApiResponse(responseCode = "400", description = "已申请"),
            @ApiResponse(responseCode = "404", description = "未申请租房"),
            @ApiResponse(responseCode = "500", description = "申请失败")
    })
    @PostMapping("/apply")//http://localhost:8089/main/rental/apply
    public CommonResult applyIn(@RequestBody RentalApplication application) {
        CommonResult commonResult = new CommonResult();
        try{
            long tenantId = application.getTenantId();
            long houseId = application.getHouseId();
            String type = application.getType();
            if(type.equals("in")){
                RentalApplication rentalApplication = rentalApplicationService.findByTenantIdAndHouseIdAndType(tenantId, houseId, "in");
                if(rentalApplication == null){
                    rentalApplicationService.apply(application);
                    commonResult.setCode(200);
                    commonResult.setMsg(("申请成功"));
                }
                else{
                    commonResult.setCode(400);
                    commonResult.setMsg("请勿重复申请");
                }
            }
            else if(type.equals("out")){
                RentalApplication ex = rentalApplicationService.findByTenantIdAndHouseIdAndType(tenantId, houseId, "out");
                RentalApplication rentalApplication = rentalApplicationService.findByTenantIdAndHouseIdAndType(tenantId, houseId, "in");
                if(ex != null){
                    commonResult.setCode(400);
                    commonResult.setMsg("请勿重复申请");
                }else if(rentalApplication != null && rentalApplication.getStatus().equals("approved")){
                    long id = rentalApplication.getApplicationId();
                    rentalApplicationService.delete(id);
                    rentalApplicationService.apply(application);
                    commonResult.setCode(200);
                    commonResult.setMsg("申请成功");
                }
                else{
                    commonResult.setCode(404);
                    commonResult.setMsg("未申请租房");
                }
            }
        }catch (Exception e){
            commonResult.setCode(500);
            commonResult.setMsg("申请失败");
        }
        return commonResult;
    }

    @Operation(summary = "审核申请")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "审核成功"),
            @ApiResponse(responseCode = "500", description = "审核失败")
    })
    @PutMapping("/judge")//http://localhost:8089/main/rental/judge
    public CommonResult approve(@RequestParam long rentalApplicationId, @RequestParam String status) {
        CommonResult commonResult = new CommonResult();
        try{
            RentalApplication rentalApplication = rentalApplicationService.findById(rentalApplicationId);
            String type = rentalApplication.getType();
            long houseId = rentalApplication.getHouseId();
            if(type.equals("in")){
                rentalApplicationService.updateStatus(rentalApplicationId,status);
                if(status.equals("approved")){
                    houseService.updateStatus(houseId, "rented");
                    commonResult.setCode(200);
                    commonResult.setMsg("已通过");
                }
                else if(status.equals("rejected")){
                    houseService.updateStatus(houseId, "available");
                    commonResult.setCode(201);
                    commonResult.setMsg("已拒绝");
                }
            }else{
                rentalApplicationService.updateStatus(rentalApplicationId,status);
                if(status.equals("approved")){
                    houseService.updateStatus(houseId, "available");
                    Record record = new Record();
                    long tenantId = rentalApplication.getTenantId();
                    record.setHouseId(houseId);
                    record.setTenantId(tenantId);
                    recordService.add(record);
                    rentalApplicationService.delete(rentalApplicationId);
                    commonResult.setCode(200);
                    commonResult.setMsg("已通过");
                }
                else if(status.equals("rejected")){
                    houseService.updateStatus(houseId, "pending");
                    commonResult.setCode(201);
                    commonResult.setMsg("已拒绝");
                }
            }

        }catch (Exception e){
            commonResult.setCode(500);
            commonResult.setMsg("审核失败");

        }
        return commonResult;
    }

    @Operation(summary = "根据租客ID查询")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    @GetMapping("/tenant/{tenantId}")//http://localhost:8089/main/rental/tenant/{tenantId}
    public CommonResult getByTenant(@PathVariable long tenantId) {
        CommonResult commonResult = new CommonResult();
        try{
            List<RentalApplication> list = rentalApplicationService.findByTenantId(tenantId);
            commonResult.setCode(200);
            commonResult.setMsg("查询成功");
            commonResult.setData(list);
        }catch (Exception e){
            commonResult.setCode(500);
            commonResult.setMsg("查询失败");
        }
        return commonResult;
    }

    @Operation(summary = "根据房源ID查询")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    @GetMapping("/house/{houseId}")//http://localhost:8089/main/rental/house/{houseId}
    public CommonResult getByHouse(@PathVariable long houseId) {
        CommonResult commonResult = new CommonResult();
        try{
            List<RentalApplication> list = rentalApplicationService.findByHouseId(houseId);
            commonResult.setCode(200);
            commonResult.setMsg("查询成功");
            commonResult.setData(list);
        }catch (Exception e){
            commonResult.setCode(500);
            commonResult.setMsg("查询失败");
        }
        return commonResult;
    }

    @Operation(summary = "根据房东ID查询")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    @GetMapping("/landlord/{landlordId}")//http://localhost:8089/main/rental/landlord/{landlordId}
    public CommonResult getByLandlord(@PathVariable long landlordId) {
        CommonResult commonResult = new CommonResult();
        try{
            List<House> houses = houseService.findByLandlordId(landlordId);
            List<RentalApplication> list = new ArrayList<>();
            for(House house : houses){
                long id = house.getHouseId();
                List<RentalApplication> current = rentalApplicationService.findByHouseId(id);
                list.addAll(current);
            }
            commonResult.setCode(200);
            commonResult.setMsg("查询成功");
            commonResult.setData(list);
        }catch (Exception e){
            commonResult.setCode(500);
            commonResult.setMsg("查询失败");
        }
        return commonResult;
    }

    @Operation(summary = "查询所有")
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "查询失败")
    })
    @GetMapping("/findAll")//http://localhost:8089/main/rental/findAll
    public CommonResult findAll() {
        CommonResult commonResult = new CommonResult();
        try{
            List<RentalApplication> rentalApplications = rentalApplicationService.findAll();
            commonResult.setCode(200);
            commonResult.setMsg("查询成功");
            commonResult.setData(rentalApplications);
        }catch (Exception e) {
            commonResult.setCode(500);
            commonResult.setMsg("查询失败");
        }
        return commonResult;
    }

    @Operation(summary = "删除租房记录")
    @ApiResponses({
            @ApiResponse(responseCode = "200",description = "删除成功"),
            @ApiResponse(responseCode = "500",description = "删除失败")
    })
    @DeleteMapping("/delete/{rentalApplicationId}")//http://localhost:8089/main/rental/delete/{rentalApplicationId}
    public CommonResult deleteById(@PathVariable long rentalApplicationId) {
        CommonResult commonResult = new CommonResult();
        try{
            rentalApplicationService.delete(rentalApplicationId);
            commonResult.setCode(200);
            commonResult.setMsg("删除成功");
        }catch (Exception e) {
            commonResult.setCode(500);
            commonResult.setMsg("删除失败");
        }
        return commonResult;
    }

}
